import MessageHandler
import Logger
import Config
import Pinger

class Pinger:
    
    def __init__(self, handler, logger, mSender):
        pinger = Thread(target = self.loop)
        self.mHandler = handler
        self.logger = logger
        self.mSender = mSender
        
    # voor de Thread
    def run():
        logger.add_queue("Ping thread started", "Pinger")
        while True:
            now = time.time()
            
            # pseudocode
            # waar moet het IP adres en de poort van "deze" server opgeslagen worden?
            # get all servers/nodes from the tree
            # if no connection for 32 seconds
                # disconnect
            # else
                # send ping message
            
            # get keys (that represent names of the clients) from the database
            clients_names = mHandler.clientDBN.keys()
            
            for server in mHandler.serverdb:
                
                # TODO: hoe kan je erachter komen 1. is server parent?
                # 2. hoe lang geleden reageerde de server voor het laats?
                if (now - server['last_updated'] > 32):
                    logger.add_queue("Server "+server['ip']+" 32 seconds inactive.", "Pinger")
                    
                    # is this server a parent?
                    if (server['is_parent'])
                        # TODO
                    mHandler.serverdb.remove(server)

            for client in mHandler.clientDBN:
                if (now - client['last_updated'] > 32):
                    logger.add_queue("Client "+client['name']+" 32 seconds inactive.", "Pinger")
                    
                    # remove this client from global list of clientDBN
                    mHandler.clientDBN.remove(client)
                    
                    # send notification to the rest of the clients
                    for c in mHandler.clientDBA:
                        address, pw = c['name']
                        
                        # TODO: how can you get the key?
                        msg = "Sending a 130 to: "+address+" with name: "+c[]+\
                        "and message: \"Client not responding\""
                                                
                        mSender.add_queue(msg, address)
                        

            time.sleep(0.5)
        logger.add_queue("Ping thread exited", "Pinger")
